package rabid;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;


public class Similar {

	Vector Results;
	int similiarity[];
	int compareFile;
	String[] files;
	
	public Similar(HashMap corpusWords, int numFiles, String[] corpusFiles, int file){
		Results = new Vector();	
		similiarity = new int[numFiles];
		compareFile = file;
				
		setsimiliarity(corpusWords);
		setResults();
		
		files = new String[Results.size()];

		for(int i=0;i<Results.size();i++){
			files[i] = corpusFiles[((Integer)Results.get(i)).intValue()]; 
		}
		
	}//end constructor
	
	private void setsimiliarity(HashMap corpusWords){
		int i;
		int[] counts;
				
		Iterator iter = corpusWords.keySet().iterator();
		while(iter.hasNext()) {
			String s = (String) iter.next();
			counts = (int[]) corpusWords.get(s);
			
				if(counts[compareFile] > 0) {
					for(i=0;i<counts.length;i++){
						if(counts[i] > 0)
							similiarity[i]++;
					}
				}
		}
		//we already know the file is similiar to itself!!
		similiarity[compareFile] = 0;
		
		for(i=0;i<similiarity.length;i++)
			System.out.print(similiarity[i] +" ");
		System.out.print("\n");
		
	}//end setsimiliarity()
	
	private void setResults(){
		int currIndex=0;
		int currResult=0;
		int comparator=0;
		Integer tempInteger;
		boolean countGreater7=true;
		
		//initialize arrayResults
		while(currResult<7 && countGreater7){
			if(similiarity[currIndex]==0)
				currIndex++;
			else
			{
				tempInteger = new Integer(currIndex);
				Results.add(tempInteger);
				currResult++;
				currIndex++;				
				
			}
			if(currIndex == similiarity.length)
				countGreater7 = false;
		}	
		
		sortResults();
		
		if(countGreater7)
		{
			while(currIndex<similiarity.length){
				tempInteger = (Integer)Results.get(6);
				comparator = similiarity[tempInteger.intValue()];
				if(similiarity[currIndex] > comparator){
					tempInteger = new Integer(currIndex); 
					Results.set(6, tempInteger);
					sortResults();
				}
				currIndex++;
			}
			
		}
	}//end setResults()
	
	private void sortResults()
	{
		boolean hasSwapped = true;
		Integer holder;
		int i,compare1,compare2;
		
		while(hasSwapped){
			
			hasSwapped = false;
			for(i=0;i< Results.size()-1;i++){
				
				holder = (Integer)Results.get(i);
				compare1 = holder.intValue();
				holder = (Integer)Results.get(i+1);
				compare2 = holder.intValue();
				if(similiarity[compare1] < similiarity[compare2]){
					
					Results.set(i+1, (Integer)Results.get(i));
					Results.set(i, holder);
					hasSwapped=true;
				}//end if x > 0
			}//end for loop
		}//end while
		
	}//end sortResults()

	public String[] getFiles(){
		return files;
	}//end getResults()
}
